package com.block.risk.service.type;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.block.common.service.LogFactory;
import com.block.db.entity.MemberExtInfo;
import com.block.db.entity.RiskConfigInfo;
import com.block.db.entity.RiskResultInfo;
import com.block.db.mapper.RiskConfigInfoMapper;
import com.block.db.mapper.RiskResultInfoMapper;
import com.block.risk.model.param.RiskControlParam;
import com.block.risk.model.result.RiskControlResult;
import com.block.risk.model.result.RiskJudgeResult;
import com.block.risk.service.IRiskResultInfoService;
import com.block.risk.service.IRiskService;
import com.block.risk.service.type.utils.ZaiYangMD5Util;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/***
 * 杭州阳载 蹭河北风控
 */
@Service
public class ZaiYangRiskService implements IRiskService {

    private static Logger log = LogFactory.getCommLog();

    private static String CONFIG_ID_QUANJING = "2";

    private static String CONFIG_ID_QUANJING_QUERY = "3";

    private static String CONFIG_ID_QUANJING_SELF = "4";

//    private List<String> valueList = Arrays.asList("0", "(0,500)", "[500,1000)");
    private List<String> valueList = Arrays.asList("0", "(0,500)");

    private List<String> valueListSelf = Arrays.asList("0", "(0,500)");

    @Autowired
    IRiskResultInfoService riskResultInfoService;
    @Resource
    RiskResultInfoMapper riskResultInfoMapper;
    @Resource
    RiskConfigInfoMapper riskConfigInfoMapper;

    @Override
    public RiskControlResult riskHandlerExec(RiskControlParam riskParamInfo) {

        RiskControlResult controlResult = new RiskControlResult();
        controlResult.setSuccess(false);

        MemberExtInfo memberExtInfo = riskParamInfo.getMemberExtInfo();
        RiskResultInfo riskResultInfoQuery =  riskResultInfoMapper.getEntityByConfigIdAndUid(CONFIG_ID_QUANJING_QUERY, memberExtInfo.getUid());
        if (ObjectUtil.isNotEmpty(riskResultInfoQuery)){
            if (ObjectUtil.equals(Integer.valueOf(1), riskResultInfoQuery.getStatus())){
                // 风控查询不为空，且风控通过
                controlResult.setMessage("风控通过");
                controlResult.setSuccess(true);
            }else {
                // 风控查询不为空，且风控通过
                controlResult.setMessage(riskResultInfoQuery.getMessage());
            }
            return controlResult;
        }

        // 查询风控结果
        RiskResultInfo riskResultInfo = this.queryQuanJingResult(memberExtInfo, riskParamInfo);
        if (ObjectUtil.isNotEmpty(riskResultInfo)){
            if (ObjectUtil.equals(Integer.valueOf(0), riskResultInfo.getStatus())){
                controlResult.setMessage(riskResultInfo.getMessage());
                return controlResult;
            }

            controlResult.setSuccess(true);
            controlResult.setMessage("杭州载阳风控通过");
            return controlResult;
        }

        /**
         * 阳载的数据过风控
         */
        RiskResultInfo riskResultInfoSelfQuan =  riskResultInfoMapper.getEntityByConfigIdAndUid(CONFIG_ID_QUANJING_SELF, memberExtInfo.getUid());
        if (ObjectUtil.isEmpty(riskResultInfoSelfQuan)){
            // 查到结果
            riskResultInfoSelfQuan  = this.queryQuanJingResultZaiYangSelf(memberExtInfo, riskParamInfo);
            if (ObjectUtil.isEmpty(riskResultInfoSelfQuan)){
                controlResult.setMessage("杭州载阳self风控结果为空");
                return controlResult;
            }
        }

        if (!ObjectUtil.equals(Integer.valueOf(1), riskResultInfoSelfQuan.getStatus())){
            controlResult.setMessage(riskResultInfoSelfQuan.getMessage());
            return controlResult;
        }

        controlResult.setSuccess(true);
        controlResult.setMessage("杭州载阳self风控通过");
        return controlResult;

    }


    private RiskResultInfo queryQuanJingResult(MemberExtInfo memberExtInfo, RiskControlParam riskParamInfo){

        RiskConfigInfo riskConfigInfo = riskConfigInfoMapper.selectById(CONFIG_ID_QUANJING_QUERY);
        // 查询该数据的结果

        RiskResultInfo riskResultInfo = new RiskResultInfo();
        riskResultInfo.setConfigId(riskConfigInfo.getId());
        riskResultInfo.setDataId(riskParamInfo.getDataId());
        riskResultInfo.setDataType(riskParamInfo.getDataType());

        riskResultInfo.setUid(memberExtInfo.getUid());
        riskResultInfo.setUsername(memberExtInfo.getUsername());
        riskResultInfo.setMobile(memberExtInfo.getMobile());
        riskResultInfo.setIdcard(memberExtInfo.getIdCard());

        RiskResultInfo riskResultInfoQuanJing =  riskResultInfoMapper.getEntityByConfigIdAndUid(CONFIG_ID_QUANJING, memberExtInfo.getUid());
        if (ObjectUtil.isEmpty(riskResultInfoQuanJing)){
            // 没有风控结果
//            riskResultInfo.setStatus(0);
//            riskResultInfo.setMessage("无风控结果");
            return null;
        }else{
            riskResultInfo.setCode(riskResultInfoQuanJing.getCode());
            riskResultInfo.setMessage(riskResultInfoQuanJing.getMessage());
            riskResultInfo.setResult(riskResultInfoQuanJing.getResult());
            riskResultInfo.setResultInfo(riskResultInfoQuanJing.getResultInfo());

            // 风控结果判断
            RiskJudgeResult riskJudgeResult = this.riskControlQuanJingQuery(riskResultInfo);
            riskResultInfo.setStatus(riskJudgeResult.isPass()?1:0);
            riskResultInfo.setMessage(riskJudgeResult.getResult());
        }

        boolean save = riskResultInfoService.save(riskResultInfo);
        if (!save){
            return null;
        }
        return riskResultInfo;
    }

    private RiskJudgeResult riskControlQuanJingQuery(RiskResultInfo riskResultInfo){
        RiskJudgeResult riskJudgeResult = new RiskJudgeResult();
        riskJudgeResult.setPass(false);

        String code = riskResultInfo.getCode();
        if (!StrUtil.equals(code, "20000")){
            riskJudgeResult.setResult(riskResultInfo.getMessage());
            return riskJudgeResult;
        }

        String resultInfo = riskResultInfo.getResult();
        try {
            JSONObject jsonObject = JSON.parseObject(resultInfo);

            JSONObject currentReportDetail = jsonObject.getJSONObject("current_report_detail");
            JSONObject behaviorReportDetail = jsonObject.getJSONObject("behavior_report_detail");
            JSONObject applyReportDetail = jsonObject.getJSONObject("apply_report_detail");

            if (ObjectUtil.isEmpty(behaviorReportDetail)){
                riskJudgeResult.setResult("行为数据结果为空；【behavior_report_detail】");
                return riskJudgeResult;
            }

            // 近一个月还款金额大于1000
            // 近1个月履约贷款总金额
            String amountSettle = behaviorReportDetail.getString("B22170040");
            if (valueList.contains(amountSettle)){
                riskJudgeResult.setResult(StrUtil.format("近1个月履约贷款总金额；【{}】", amountSettle));
                return riskJudgeResult;
            }

            // 订单结清笔数8笔以上
            // 贷款已结清订单数
//            String numberSettle = behaviorReportDetail.getString("B22170052");
//            if (Integer.valueOf(numberSettle) < 5){
//                riskJudgeResult.setResult(StrUtil.format("订单结清笔数8笔以上不通过；【{}】", numberSettle));
//                return riskJudgeResult;
//            }

            // 订单比例90以上
            // 正常还款订单数占贷款总订单数比例
//            String numberRate = behaviorReportDetail.getString("B22170034");
//            numberRate = numberRate.replace("%", "");
//            if (Integer.valueOf(numberRate) < 80){
//                riskJudgeResult.setResult(StrUtil.format("订单比例90以上不通过；【{}】", numberRate));
//                return riskJudgeResult;
//            }

//            // 近6个月逾期M0 = 0
//            String numberSixM0 = behaviorReportDetail.getString("B22170025");
//            if (Integer.valueOf(numberSixM0) > 0){
//                riskJudgeResult.setResult(StrUtil.format("近6个月逾期M0不通过；【{}】", numberSixM0));
//                return riskJudgeResult;
//            }
//
//            // 近一个月贷款机构放款笔数1笔以上
//            String numberLoanOne = behaviorReportDetail.getString("B22170002");
//            if (Integer.valueOf(numberLoanOne) == 0){
//                riskJudgeResult.setResult(StrUtil.format("近一个月贷款机构放款笔数1笔以上不通过；【{}】", numberLoanOne));
//                return riskJudgeResult;
//            }
//
//            // 成功扣款笔数大于失败笔数.
//            String numberSuccess = behaviorReportDetail.getString("B22170045");
//            String numberFailed = behaviorReportDetail.getString("B22170035");
//            if (Integer.valueOf(numberFailed) >= Integer.valueOf(numberSuccess)){
//                riskJudgeResult.setResult(StrUtil.format("成功扣款笔数大于失败笔数不通过；成功扣款笔数【{}】失败笔数【{}】", numberSuccess, numberFailed ));
//                return riskJudgeResult;
//            }

            riskJudgeResult.setPass(true);
            riskJudgeResult.setResult(StrUtil.format("全景分控通过:【{}】", amountSettle));
            return riskJudgeResult;
        }catch (JSONException exception){
            exception.printStackTrace();
            riskJudgeResult.setResult(riskResultInfo.getResult());
        }
        return riskJudgeResult;
    }


    private RiskResultInfo queryQuanJingResultZaiYangSelf(MemberExtInfo memberExtInfo, RiskControlParam riskParamInfo){

        RiskConfigInfo riskConfigInfo = riskConfigInfoMapper.selectById(CONFIG_ID_QUANJING_SELF);
        // 查询该数据的结果

        String hostUrl = riskConfigInfo.getRequestUrl();
        String timestamp = String.valueOf(System.currentTimeMillis());

        String orderNo = RandomUtil.randomString(28);
        Map<String, String> paramMap = new HashMap<>();

        paramMap.put("member_id", riskConfigInfo.getAppCode());
        paramMap.put("appid", riskConfigInfo.getAppKey());
        paramMap.put("secret", riskConfigInfo.getAppSecret());

        paramMap.put("timestamp", timestamp);
        paramMap.put("trans_id", orderNo);

        paramMap.put("id_no", memberExtInfo.getIdCard());
        paramMap.put("name", memberExtInfo.getUsername());
        paramMap.put("phone_no", memberExtInfo.getMobile());

        List<String> keyList = JSON.parseArray(JSON.toJSONString(paramMap.keySet()), String.class);
        Collections.sort(keyList);
        StringBuilder sb = new StringBuilder();
        for (String key: keyList){
            sb.append(key).append("=").append(paramMap.get(key)).append("&");
        }

        String substring = sb.toString();

        String sign = ZaiYangMD5Util.string2MD5(substring);
        paramMap.put("sign", sign);
        paramMap.remove("secret");

        StringBuilder requestUrl = new StringBuilder(hostUrl);
        for (String key: paramMap.keySet()){
            requestUrl.append("&").append(key).append("=").append(paramMap.get(key));
        }

        String url = requestUrl.toString();
        String response = HttpUtil.createGet(url)
                .header("Content-Type", "application/json")
                .execute().body();
        log.info("【杭州阳载】【风控数据查询】全景【requestUrl】{}【paramMap】{}【response】{}", url, JSON.toJSONString(paramMap), response);

        JSONObject jsonObject = JSON.parseObject(response);
        String code = jsonObject.getString("code");
        String data = jsonObject.getString("data");
        String message = jsonObject.getString("message");

        RiskResultInfo riskResultInfo = new RiskResultInfo();
        riskResultInfo.setConfigId(riskConfigInfo.getId());
        riskResultInfo.setDataId(riskParamInfo.getDataId());
        riskResultInfo.setDataType(riskParamInfo.getDataType());

        riskResultInfo.setUid(memberExtInfo.getUid());
        riskResultInfo.setUsername(memberExtInfo.getUsername());
        riskResultInfo.setMobile(memberExtInfo.getMobile());
        riskResultInfo.setIdcard(memberExtInfo.getIdCard());
        riskResultInfo.setCode(code);
        riskResultInfo.setMessage(message);
        riskResultInfo.setResult(data);
        riskResultInfo.setResultInfo(response);
        riskResultInfo.setParamInfo(JSON.toJSONString(paramMap));

        // 风控结果判断
        RiskJudgeResult riskJudgeResult = this.riskControlQuanJingZaiYangSelf(riskResultInfo);
        riskResultInfo.setStatus(riskJudgeResult.isPass()?1:0);
        riskResultInfo.setMessage(riskJudgeResult.getResult());

        boolean save = riskResultInfoService.save(riskResultInfo);
        if (!save){
            return null;
        }
        return riskResultInfo;
    }

    private RiskJudgeResult riskControlQuanJingZaiYangSelf(RiskResultInfo riskResultInfo){
        RiskJudgeResult riskJudgeResult = new RiskJudgeResult();
        riskJudgeResult.setPass(false);

        String code = riskResultInfo.getCode();
        if (!StrUtil.equals(code, "0")){
            riskJudgeResult.setResult(riskResultInfo.getMessage());
            return riskJudgeResult;
        }

        String resultInfo = riskResultInfo.getResult();
        try {
            JSONObject jsonObject = JSON.parseObject(resultInfo);

            // 近一个月还款金额大于1000
            // 近1个月履约贷款总金额
            String amountSettle = jsonObject.getString("b22170040");
            if (StrUtil.isEmpty(amountSettle)){
                riskJudgeResult.setResult("近1个月履约贷款总金额；风控结果为空 b22170040");
                return riskJudgeResult;
            }
            if (valueListSelf.contains(amountSettle)){
                riskJudgeResult.setResult(StrUtil.format("近1个月履约贷款总金额；【{}】", amountSettle));
                return riskJudgeResult;
            }

            riskJudgeResult.setPass(true);
            riskJudgeResult.setResult(StrUtil.format("全景分控通过:【{}】", amountSettle));
            return riskJudgeResult;
        }catch (JSONException exception){
            exception.printStackTrace();
            riskJudgeResult.setResult("异常："+riskResultInfo.getResult());
        }
        return riskJudgeResult;
    }

}
